這個方法實在太扯了,他很明顯的有分成三個區塊,
defp calculate_score(%{host: %{desk: host_desk}, guest: %{desk: guest_desk}, round: round}) do
[host_cards, guest_cards] =
Enum.map([host_desk, guest_desk], &Enum.slice(&1, (round - 1)..(round * 3 - 1)))
[host_score, guest_score] =
[host_cards, guest_cards]
|> Enum.map(&Enum.reject(&1, fn card -> card == :reverse end))
|> Enum.map(&Enum.sum(&1))
reverse =
[host_desk, guest_desk]
|> Enum.map(&Enum.filter(&1, fn card -> card == :reverse end))
|> List.flatten()
|> length()
|> rem(2) == 1
%{host: host_score, guest: guest_score, reverse: reverse}
end
我把檢查 reverse 跟 算分數 拆開成方法
defp reverse?(desk) do
desk
|> Enum.filter(&(&1 == :reverse))
|> length()
|> rem(2) == 1
end
defp get_score(desk) do
desk
|> Enum.reject(&(&1 == :reverse))
|> Enum.sum()
end
把限制範圍放在 呼叫上兩個方法的前面
defp add_wins(%{turn: turn, round: round, host: host, guest: guest} = game) when turn > 3 do
range_start = (round - 1) * 3
range = range_start..(range_start + 2) # 取該局的範圍
host_desk = Enum.slice(host.desk, range)
guest_desk = Enum.slice(guest.desk, range)
# 原本的統一從傳回來的值拿結果,改成直接呼叫方法。
if apply_reverse(
get_score(host_desk) > get_score(guest_desk),
reverse?(host_desk ++ guest_desk)
) do
assign_to_player(game, :host, :wins, game.host.wins + 1)
else
assign_to_player(game, :guest, :wins, game.guest.wins + 1)
end
end
都連線遊戲了,總不能讓對方一直等
我想做成,每個 turn 如果 30 秒內沒有出牌的話,系統幫你隨機出
之後想要的話再看看要不要做成可以調整時限,
要做的事情大概是
在遊戲開始與換回合的時候使用 Process.send_after
Process.send_after(self(), {:times_up, :host, 1, 1}, 30000)
第三個變數是時間,單位為毫秒
再使用 handle_info 接收定時隨機出牌的命令
def handle_info({:times_up, :host, round, turn}, game) do
# 檢查他在指定 round 的指定 turn 有沒有出牌了
# 沒有的話幫 host 出牌
end
明天來試試看這個方向好不好做